package org.framework.server.util.dao.sql.support.sort;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.framework.core.util.StringUtil;
import org.framework.define.param.SortParam;

public class Sort implements SortFilter {
	
	protected List<String> columns;
	
	public Sort(String sortColumn) {
		if(sortColumn != null && !sortColumn.equals("")) {
			columns = new ArrayList<String>();
			columns.add(sortColumn);
		}
	}
	
	public Sort(Map<String,String> params) {
		columns = new ArrayList<String>();
		this.columns.add(params.get(new SortParam().getValue()));
	}

	@Override
	public String toSql() {
		if(this.columns == null || this.columns.size() == 0)
			return "";
		
		StringBuffer sb = new StringBuffer(" ");

		for (String column : columns) {
			if(column != null && !column.equals("")) {
				String[] order = StringUtil.split(column, ",");// column.split(",");
				
				if(order.length > 0 && !order[0].equals(""))
					sb.append(order[0]);
				
				if(order.length > 1 && !order[1].equals(""))
					sb.append(" ").append(order[1].toUpperCase());
				
				if(order.length > 0 && !order[0].equals(""))
					sb.append(",");
			}
		}
		sb.delete(sb.length() - 1, sb.length());
		
		return sb.toString().equals("")? "" : "ORDER BY" + sb.toString();
	}

	public List<String> getColumns() {
		return columns;
	}

	public void setColumns(List<String> columns) {
		this.columns = columns;
	}
}
